package app.texas.com.devilfishhouse.View.Fragment.home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.universal_library.fragment.BaseFragment;
import com.universal_library.weight.WrapContentLinearLayoutManager;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.util.ArrayList;
import java.util.List;

import app.texas.com.devilfishhouse.Base.BaseFragmentView;
import app.texas.com.devilfishhouse.Base.BasePresenter;
import app.texas.com.devilfishhouse.Beans.BannerBean;
import app.texas.com.devilfishhouse.Beans.HotLineBean;
import app.texas.com.devilfishhouse.Beans.HotShopBean;
import app.texas.com.devilfishhouse.R;
import app.texas.com.devilfishhouse.myUtils.WLogger;
import app.texas.com.devilfishhouse.ui.SimpleBackPage;
import app.texas.com.devilfishhouse.ui.UiHelper;
import app.texas.com.devilfishhouse.weight.BannerView;
import app.texas.com.devilfishhouse.weight.FlipperTextView;
import app.texas.com.devilfishhouse.weight.MyGridView;
import butterknife.BindView;

/**
 * Created by solin on 2018/7/16.
 * 首页
 */

public class HomeFragmentView extends BaseFragmentView {
    HomePresenter presenter;

    @BindView(R.id.bannerView)
    BannerView bannerView;

    @BindView(R.id.marqueeView)
    FlipperTextView marqueeView;

    @BindView(R.id.gridview)
    MyGridView gridview;

    @BindView(R.id.recycleview_hotShop)
    RecyclerView recycleview_hotShop;

    @BindView(R.id.bmapView)
    MapView mMapView;

    private HotShopRecycleViewAdapter hotshopAdapter;
    private BaiduMap mBaiduMap;
    private LocationClient mLocationClient;
    private MyLocationListener myListener;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        initHotShopRecycleView();
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);//普通地图
        mLocationClient = new LocationClient(getActivity().getApplicationContext()); // 声明LocationClient类
        myListener = new MyLocationListener();
        mLocationClient.registerLocationListener(myListener); // 注册监听函数
        mLocationClient.setLocOption(InitLocOption());
        mLocationClient.start();// 开始定位
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        SDKInitializer.initialize(getActivity().getApplicationContext());
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    /**
     * 初始化热门店铺
     */
    public void initHotShopRecycleView() {
        DefaultItemDecoration defaultItemDecoration = new DefaultItemDecoration(getResources().
                getColor(R.color.white), 10, 10, -1);
        LinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(getContext(),
                LinearLayoutManager.HORIZONTAL, false);
        recycleview_hotShop.setLayoutManager(linearLayoutManager);
        recycleview_hotShop.addItemDecoration(defaultItemDecoration);
        hotshopAdapter = new HotShopRecycleViewAdapter(mContext);
        recycleview_hotShop.setAdapter(hotshopAdapter);
        hotshopAdapter.setItemClickListener(new OnMyRecycleViewItemClickListener() {
            @Override
            public void onItemClickListener(int position) {
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.HOUSEINFO, null);
            }
        });
    }

    private void click(int position) {
        switch (position) {
            case 0:
                //新房
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.NEWHOUSE, null);
                break;
            case 1:
                //二手房
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.ERSHOUFANG, null);
                break;
            case 2:
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.FINANCIAL, null);
                break;
            case 3:
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.ACTIONFRAGMENT, null);
                break;
            case 4:
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.HOTLINENEWS, null);
                break;
            case 5:
                //滴滴房产
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.DIDIFRAGMENT, null);
                break;
            case 6:
                //附近服务
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.NEARBYSEVICE, null);
                break;
            case 7:
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.MYHOUSELIST, null);
                break;
            default:
                break;
        }
    }

    @Override
    protected BasePresenter getPresenter() {
        presenter = new HomePresenter(this);
        return presenter;
    }

    @Override
    protected void initData() {
        presenter.getBanner("");
        presenter.getHotline("");
        gridview.setAdapter(new GridViewAdapter());
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                WLogger.log("gridView点击了" + position + "id=" + id);
                click(position);
            }
        });

        List<HotShopBean> hotShopBeans = new ArrayList<>();
        hotShopBeans.add(new HotShopBean());
        hotShopBeans.add(new HotShopBean());
        hotShopBeans.add(new HotShopBean());
        hotshopAdapter.setDatas(hotShopBeans);
        marqueeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WLogger.log("点击了：" + marqueeView.getCurrentPosition());
                UiHelper.shoSimpleBack(mContext, SimpleBackPage.HEADLINEINFO, null);
            }
        });
    }

    /**
     * banner  的数据
     */
    public void setBanner(List<BannerBean> banners) {
        if (banners.size() > 0) {
            WLogger.log("banan:" + banners.get(0).getUrl());
            bannerView.setdata(banners);
        }
    }

    public void setHotLine(List<HotLineBean> hotLine) {
        WLogger.log("热门头条：" + hotLine.size());
        marqueeView.setData(hotLine);
        marqueeView.setFlipInterval(5000);
        marqueeView.startFlipping();
    }

    private String[] itemString = new String[]{"新楼盘", "二手房", "金融产品", "促销活动", "新闻资讯",
            "滴滴房产", "附近服务", "我的房源"};

    public int[] itemIcon = new int[]{R.mipmap.new_house, R.mipmap.er_shoufang, R.mipmap.jinrong,
            R.mipmap.home_action, R.mipmap.home_news, R.mipmap.didifangchan,
            R.mipmap.fujin, R.mipmap.myhouse};

    class GridViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return itemIcon.length;
        }

        @Override
        public Object getItem(int position) {
            return itemIcon[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            HolderView myview = null;
            if (myview == null) {
                myview = new HolderView();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.gridview_item, null);
                convertView.setTag(myview);
            } else {
                myview = (HolderView) convertView.getTag();
            }
            myview.iv_icon = convertView.findViewById(R.id.iv_gridview_icon);
            myview.tv_itemString = convertView.findViewById(R.id.tv_gridview_text);
            myview.iv_icon.setImageResource(itemIcon[position]);
            myview.tv_itemString.setText(itemString[position]);
            return convertView;
        }

        class HolderView {
            private TextView tv_itemString;
            private ImageView iv_icon;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        if (mLocationClient != null && mLocationClient.isStarted()) {
            if (myListener != null) {
                mLocationClient.unRegisterLocationListener(myListener);
            }
            mLocationClient.stop();
            mLocationClient = null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    /////////////////////百度定位////////////////////
    private LocationClientOption InitLocOption() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//默认高精度定位模式
        option.setCoorType("bd09ll");//默认gcj02，设置返回的定位结果坐标系
        option.setScanSpan(1000);//默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms
        option.setIsNeedAddress(true);//设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//默认false,设置是否使用gps
        option.setLocationNotify(true);//默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//默认false，设置是否需要位置语义化结果
        option.setIsNeedLocationPoiList(true);//默认false，设置是否需要POI结果
        option.setIgnoreKillProcess(false);//默认true不杀死进程，设置是否在stop的时候杀死进程
        option.SetIgnoreCacheException(false);//默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//默认false，设置是否需要过滤GPS仿真结果，默认需要
        return option;
    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                Toast.makeText(mContext, "location is null", Toast.LENGTH_SHORT).show();
                return;
            }
            BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher);
            LatLng latlng = new LatLng(location.getLatitude(), location.getLongitude());//创建一个图层选项
            OverlayOptions options = new MarkerOptions().position(latlng).icon(bitmapDescriptor);
            mBaiduMap.addOverlay(options);
            MapStatus mMapStatus = new MapStatus.Builder().target(latlng).zoom(12).build();
            //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
            MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
            mBaiduMap.setMapStatus(mMapStatusUpdate);//改变地图状态
        }
    }
}
